package com.wang.learn.cloudredis.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.*;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.wang.learn.cloudredis.constant.AliyunOSSConstants;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * ClassName AliyunOSSUtil
 * Description
 *
 * @author wang
 * Date 2021/9/2 19:13
 */
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    /**
     * 上传文件
     */
    public static String upLoad(MultipartFile file) {
        logger.info("------OSS文件上传开始--------" + file.getName());

        String endPoint = AliyunOSSConstants.END_POINT;
        String accessKeyId = AliyunOSSConstants.ASSCESS_KEY_ID;
        String accessKeySecret = AliyunOSSConstants.ASSCESS_KEY_SECRET;
        String bucketName = AliyunOSSConstants.BUCKET_NAME;
        String fileDir = AliyunOSSConstants.FILE_DIR;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String fileUrl = null;
        OSS client = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            // 设置文件路径和名称
            fileUrl = fileDir + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + suffix);
            logger.info("fileUrl：" + fileUrl);
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file.getInputStream()));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("resp：" + JSONObject.toJSONString(result));
                logger.info("------OSS文件上传成功------" + AliyunOSSConstants.COMMON_URL + fileUrl);
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return AliyunOSSConstants.COMMON_URL + fileUrl;
    }

    /**
     * 删除文件
     */
    public static String delete(String fileUrl) {
        logger.info("------OSS文件删除开始--------" + fileUrl);

        String endPoint = AliyunOSSConstants.END_POINT;
        String accessKeyId = AliyunOSSConstants.ASSCESS_KEY_ID;
        String accessKeySecret = AliyunOSSConstants.ASSCESS_KEY_SECRET;
        String bucketName = AliyunOSSConstants.BUCKET_NAME;
        OSS client = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            client.deleteObject(bucketName, fileUrl);
            logger.info("------OSS文件删除成功------" + AliyunOSSConstants.COMMON_URL + fileUrl);
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return AliyunOSSConstants.COMMON_URL + fileUrl;
    }


}
